package trong.gold.soft.com.view;

import trong.gold.soft.com.main.mTetrisMidlet;

import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

public class guitangTetris extends Form implements CommandListener{
	private TextField txtgui;
	private Command guiCmd,backCmd;
	private mTetrisMidlet midlet;
	private Alert alert;
	private String nd = "TANG100021 ";
	private boolean kt=false;
	public guitangTetris(mTetrisMidlet midlet) {
		super("Gửi tặng");
		this.midlet = midlet;
		txtgui = new TextField("Nhập Số điện thoại(PhoneNumber)","",11,TextField.PHONENUMBER);
		guiCmd = new Command("Gửi",Command.OK,1);
		backCmd = new Command("Quay lại",Command.BACK,2);
		this.append(txtgui);
		this.addCommand(guiCmd);
		this.addCommand(backCmd);
		this.setCommandListener(this);
	}
	private void showalert(String a){
		alert = new Alert("Thông báo",a,null,AlertType.INFO);
		alert.setTimeout(Alert.FOREVER);
	}
	public void commandAction(Command cmd, Displayable dis) {
		if(cmd==backCmd){
			setnull();
			Runtime.getRuntime().gc();
			midlet.switchState(this,new menuTetris(midlet));
		}
		if(cmd==guiCmd){
//			if(txtgui.getString().length()<11){
//				showalert("Số điện thoại không hợp lệ");
//				midlet.showAlert(alert,this);
//			}else{
				kt=sendSms("8502",nd + txtgui.getString());
				if(kt){
					showalert("Gửi thành công");
					midlet.showAlert(alert,this);
				}else{
					showalert("Gửi không thành công");
					midlet.showAlert(alert,this);
				}
		//	}
			
		}
	}
	private boolean sendSms(String number, String message) {
        boolean result = true;
        try {
            //sets address to send message
            String addr = "sms://" + number+":5000";
            // opens connection
            MessageConnection conn = (MessageConnection) Connector.open(addr);
            // prepares text message
            TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
            //set text
            msg.setAddress(addr);
            msg.setPayloadText(message);
            // send message
            conn.send(msg);
            conn.close();
        } catch (SecurityException se) {
            result = false;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }
	private void setnull(){
		guiCmd=null;
		backCmd=null;
		txtgui=null;
	}

}
